<template>
    <div v-loading="loading">
        <el-card>
            <template #header>
                <div>添加大纲</div>
            </template>
            <el-form :rules="rules" :model="form" label-width="80px">
                <el-form-item label="大纲名称" prop="outlinename">
                    <el-input v-model="form.outlinename"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addOutlinesLoading">添加</el-button>
                    <el-button @click="$router.push({ name: 'OutlinesIndex' })">取消</el-button>
                </el-form-item>
            </el-form>
            <!-- card body -->
        </el-card>
    </div>
</template>
  
<script>
import { mapActions } from "vuex";
import { exist } from "@/api/outlines";
export default {
    data() {
        return {
            loading: false,
            form: {
                outlinename: "",
            },
            rules: {
                outlinename: [
                    { required: true, message: "大纲名不能为空" },
                    {
                        validator: (rule, value, cb) => {
                            if (/^.{1,18}$/.test(value)) {
                                cb();
                            } else {
                                cb(new Error("大纲名必须1-18个字符"));
                            }
                        },
                    },
                    {
                        validator: async (rule, value, cb) => {

                            const { data } = await exist({
                                field: "outlinename",
                                value,
                            });
                            if (data) {
                                cb(new Error("大纲名重复"));
                            } else {
                                cb();
                            }
                        },
                        trigger: "blur",
                    },
                ]
            }
        };
    },

    methods: {
        ...mapActions("outlines", ["addOutlines", 'exist']),
        async addOutlinesLoading() {
            this.loading = true;
            const data = { outlinename: this.form.outlinename }
            if (this.$route.query.id) {
                data.pid = this.$route.query.id
            };
            try {
                await this.addOutlines(data);
                this.$message.success("添加成功");
                this.$router.push({ name: 'OutlinesIndex' })
            } catch (error) { }
            this.loading = false;
        },
    },
};
</script>
  